package github.kawaiior.yuanchuxiuzhen.common.item.tools;

import github.kawaiior.yuanchuxiuzhen.common.block.ore.ManaStoneOre;
import github.kawaiior.yuanchuxiuzhen.common.capability.entity.ManaPower;
import github.kawaiior.yuanchuxiuzhen.core.init.itemgroup.YcxzGroup;
import github.kawaiior.yuanchuxiuzhen.core.registry.ModCapability;
import net.minecraft.block.BlockState;
import net.minecraft.enchantment.Enchantments;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.PickaxeItem;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.LazyOptional;

import static github.kawaiior.yuanchuxiuzhen.common.item.tools.ToolTier.VEIN_SOUL_TIER;

public class VeinSoulAxe extends PickaxeItem {
    public VeinSoulAxe() {
        super(VEIN_SOUL_TIER, 7, -2.4F, new Properties().group(YcxzGroup.YCXZ_GROUP));
    }

    private int getFragmentAmount(int level){
        switch (level) {
            case 1:
                return 1;
            case 2:
                return 2;
            case 3:
                return 3;
            case 4:
                return 5;
            case 5:
                return 7;
            case 6:
                return 9;
            case 7:
                return 12;
            case 8:
                return 18;
            case 9:
                return 25;
        }
        return 0;
    }

    private void manaHandler(World world, PlayerEntity player, int level){
        LazyOptional<ManaPower> capability = player.getCapability(ModCapability.MANA_POWER);
        capability.ifPresent((power)->{
            addFragment(world, player, level, power);
        });
    }

    private void addFragment(World world, PlayerEntity player, int level, ManaPower power){
        int amount = getFragmentAmount(level);
        power.addFragment(world, player, amount);
    }

    @Override
    public boolean onBlockDestroyed(ItemStack stack, World worldIn, BlockState state, BlockPos pos, LivingEntity entityLiving) {
        if (entityLiving instanceof  PlayerEntity){
            if (state.getBlock() instanceof ManaStoneOre){
                manaHandler(worldIn, (PlayerEntity)entityLiving, ((ManaStoneOre) state.getBlock()).getLevel());
            }
        }
        return super.onBlockDestroyed(stack, worldIn, state, pos, entityLiving);
    }

    @Override
    public void onCreated(ItemStack stack, World world, PlayerEntity player) {
        super.onCreated(stack, world, player);
        stack.addEnchantment(Enchantments.MENDING, 1);
    }
}
